//
//  QRCodeController.swift
//  Weibo
//
//  Created by zxy on 2018/12/4.
//  Copyright © 2018 zxy. All rights reserved.
//

import UIKit
import AVFoundation
import AFNetworking
class QRCodeController: UIViewController {
    @IBOutlet weak var tbBar: UITabBar!
    
    //扫一扫背景view高度约束
    @IBOutlet weak var scanBgVIewHeightCons: NSLayoutConstraint!
    //冲击波顶部约束
    @IBOutlet weak var scanLineTopCons: NSLayoutConstraint!
    //冲击波
    @IBOutlet weak var scanImageView: UIImageView!

    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置默认选中第一个item
        tbBar.selectedItem = tbBar.items![0]
        tbBar.delegate = self
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //不能放到viewDidLoad，需要等控件frame加载完毕才可以
        starAnimation()
        
        //开始扫描
        startScan()
    }
    
    //开始冲击波动画
    private func starAnimation(){
        //修改冲击波顶部约束,从顶部开始，在这里不能在约束里将顶部约束设置在顶部，因为条形码和二维码高度不一样
        self.scanLineTopCons.constant = -self.scanBgVIewHeightCons.constant
        //更新约束
        self.view.layoutIfNeeded()
        UIView.animate(withDuration: 2.0) {
            //无限循环
            UIView.setAnimationRepeatCount(MAXFLOAT)
            //修改冲击波顶部约束
            self.scanLineTopCons.constant = self.scanBgVIewHeightCons.constant
            //更新约束
            self.view.layoutIfNeeded()
        }
    }
    
    //开始扫描
    private func startScan(){
        //1.判断是否能将输入添加到会话中
        if !session.canAddInput(deviceInput!){
            return
        }
        //2.判断是否能将输出添加到会话中
        if !session.canAddOutput(output){
            return
        }
        //3.将输入/输出都添加到会话中
        session.addInput(deviceInput!)
        session.addOutput(output)
        //4.设置输出能够解析出的数据类型,availableMetadataObjectTypes:支持所有类型
        output.metadataObjectTypes = output.availableMetadataObjectTypes
        //5.设置输出代理，只要解析成功就会通知代理
        output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        
        //添加预览图层
        view.layer.insertSublayer(previewLayer, at: 0)
        
        //6.开始扫描
        session.startRunning()
    }
    
    //会话对象
    private lazy var session: AVCaptureSession = AVCaptureSession()
    
    //输入对象
    private lazy var deviceInput: AVCaptureDeviceInput? = {
        //获取摄像头
        if let device = AVCaptureDevice.default(for: AVMediaType.video){
            do{
                //拿到输入对象
                let deviceInput = try AVCaptureDeviceInput(device: device)
                return deviceInput
            }catch{
                print(error)
                return nil
            }
        }
        return nil
    }()
    
    //输出对象
    private lazy var output: AVCaptureMetadataOutput = AVCaptureMetadataOutput()
    
    //设置预览画图层
    private lazy var previewLayer: AVCaptureVideoPreviewLayer = {
        let pa = AVCaptureVideoPreviewLayer(session: session)
        pa.frame = UIScreen.main.bounds
        return pa
    }()
    
    //关闭
    @IBAction func close(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
    
    //相册
    @IBAction func photo(_ sender: Any) {
        
    }
}

//MARK:-tabBar代理方法
extension QRCodeController:UITabBarDelegate{
    //监听item切换
    func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        if item.tag == 1{//二维码
            //修改二维码/条形码背景高度约束
            self.scanBgVIewHeightCons.constant = 300
        }else{//条形码
            //修改二维码/条形码背景高度约束
            self.scanBgVIewHeightCons.constant = 150
        }
        //更新约束
        self.view.layoutIfNeeded()
        
        //在这里要先停止动画，因为冲击波默认是从高度300位置顶部开始，如果变成条形码，冲击波位置不对
        //必须先停止在开始动画，因为动画重复，默认是从初始位置开始重复
        self.scanImageView.layer.removeAllAnimations()
        //开始动画
        starAnimation()
    }
}
//MARK:-AVCaptureMetadataOutputObjectsDelegate
//扫描结果
extension QRCodeController:AVCaptureMetadataOutputObjectsDelegate{
    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection){
        //获取到扫描信息，停止扫描
//        session.stopRunning()
        
        if let metadataObject = metadataObjects.first{
            //判断当前获取到的数据对象是否是机器可以识别的类型
            if metadataObject is AVMetadataMachineReadableCodeObject{
                let result = ( metadataObject as! AVMetadataMachineReadableCodeObject).stringValue
                print(result!)
//                UIApplication.shared.openURL(URL(string: result!)!)
                
                //定位二维码
                //corners:标题扫描到二维码的四个点坐标，通过四个点的坐标绘制矩形框
//              let codeObject = previewLayer.transformedMetadataObject(for: metadataObject)! as! AVMetadataMachineReadableCodeObject
//                print(codeObject.corners)
            }
        }
    }
}
